# coding=utf-8
import json
from django import forms
from django.contrib.auth.forms import UserCreationForm, AuthenticationForm
from django.utils.translation import gettext_lazy as _
from com.kjssoft.eagleye.models import EEUser

__author__ = 'daihaibin'

class UserAuthorizeForm(AuthenticationForm):
    username = forms.EmailField(
        label=_('email_type_account'),
        help_text=_('email_type_account_help_text'),
        error_messages={
            'required':_('email_type_account_required'),
            'invalid':_('email_type_account_invalid')
        }
    )
    password = forms.CharField(
        min_length=8,
        label=_('password'),
        widget=forms.PasswordInput,
        help_text=_('account_password_help_text'),
        error_messages={
            'required':_('password_required')
        }
    )

class RegisterForm(UserCreationForm):

    username = forms.EmailField(
        label=_('email_type_account'),
        help_text=_('email_type_account_help_text'),
        error_messages={
            'required':_('email_type_account_required'),
            'invalid':_('email_type_account_invalid')
        },
    )
    password1 = forms.CharField(
        min_length=8,
        label=_('password'),
        widget=forms.PasswordInput,
        help_text=_('account_password_help_text'),
        error_messages={
            'required':_('password_required')
        }
    )
    nickname = forms.CharField(required=False, label=_('nickname'))
    check_code = forms.CharField(label=_('check_code'))

    def clean_username(self):
        """
        以用户的真实邮件地址作为用户账号
        """
        username = super(RegisterForm, self).clean_username()
        username = username.lower()
        #设置用户默认账户邮件地址为用户账户的邮件地址
        self.instance.email = username
        return username

    def clean_nickname(self):
        data = self.cleaned_data
        username = data.get('username')
        nickname = data.get('nickname')
        if not nickname or '' == str(nickname).strip():
            if username:
                nickname = str(username).strip()[0:str(username).strip().index('@')]
        return nickname.strip()

    class Meta(UserCreationForm.Meta):
        model = EEUser

class UserProfileResetForm(forms.Form):
    profiles = forms.CharField()

    def clean_profiles(self):
        profiles = self.cleaned_data.get('profiles')
        try:
            profiles = json.loads(profiles)
        except ValueError as e:
            raise forms.ValidationError(e, code=11001)
        return profiles
